<?php

class Pageley_Mock_RecordingInvocationHandler implements Pageley_Reflection_InvocationHandler {
    private $recordedInvocations;
    private $factory;
    private $recording;

    public function __construct($factory) {
        $this->recordedInvocations = new Pageley_Util_ArrayMap();
        $this->factory = $factory;
        $this->record();
    }
    
    public function invoke($proxy, $methodName, $parameters) {
        $invocationKey = "[" . $this->factory->count() . "]" . get_class($proxy) . "." . $methodName . "(" . $parameters . ")";
        if($this->recording) {
            $recording = new Pageley_Mock_Recording($invocationKey);
            $this->recordedInvocations->put($invocationKey, $recording);
            return $recording;
        } else {
            $recording = $this->recordedInvocations->shift();
            $expectedKey = "no method call";
            if($recording === null || $recording->getKey() != $invocationKey) {
                if($recording !== null) {
                    $expectedKey = "<" . $recording->getKey() . ">";
                }
                throw new Pageley_Test_AssertionException("Expected " . $expectedKey . ", found <" . $invocationKey . ">.");
            }
            $result = $recording->execute($parameters);
            return $result;
        }
        
    }
    
    public function replay() {
        $this->recording = false;
    }
    
    public function record() {
        $this->recordedInvocations->clear();
        $this->recording = true;
    }
    
    public function getRecordings() {
        return $this->recordedInvocations;
    }
}